package com.example.lenovo.weiyi;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.com.ruanmeng.demon.ChooseAnswerM;
import com.com.ruanmeng.demon.TiMuM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.view.MyListView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

/**
 * 调查(做题)
 */
public class SurveyActivity extends BaseActivity {

    @BindView(R.id.tv_survey_newnum)
    TextView tvSurveyNewnum;
    @BindView(R.id.tv_survey_allnum)
    TextView tvSurveyAllnum;
    @BindView(R.id.tv_survey_title)
    TextView tvSurveyTitle;
    @BindView(R.id.mlist_survey_tm)
    MyListView mlistSurveyTm;
    @BindView(R.id.tv_last)
    TextView tvLast;
    @BindView(R.id.tv_next)
    TextView tvNext;
    ArrayList<TiMuM.RowsBean.ChoicesBean> Temp_list = new ArrayList<>();

    private TiMuAdapter tmuadapter;
    int index;
    private int pages;
    private String tiMuId;
    private String userChoice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_survey);
        ButterKnife.bind(this);
        ChangLayTitle("调查");
        AddActivity(this);
        LayaBack();
        init();
        getData();
    }

    public void init() {
        //题目
        tmuadapter = new TiMuAdapter(Temp_list);
        mlistSurveyTm.setAdapter(tmuadapter);
        mlistSurveyTm.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            }
        });
        if (!TextUtils.isEmpty(getIntent().getStringExtra("index"))) {
            index = Integer.parseInt(getIntent().getStringExtra("index"));
        }
        //设置头部题目提示
        tvSurveyNewnum.setText("第" + (index + 1) + "题");
        if (index == 0) {
            tvLast.setVisibility(View.GONE);
        } else {
            tvLast.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 获取题目信息
     */
    public void getData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.TiMuList, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(SurveyActivity.this, "uid"));
        mRequest.add("assessId", getIntent().getStringExtra("id"));
        mRequest.add("page", index + 1);
        mRequest.add("isPager", "0");
        // 添加到请求队列
        CallServer.getRequestInstance().add(SurveyActivity.this, 0, mRequest,
                new CustomHttpListener(SurveyActivity.this, true, TiMuM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        TiMuM model = ((TiMuM) data);
                        pages = model.getPages();
                        tiMuId = model.getRows().get(0).getTiMuId();
                        tvSurveyAllnum.setText("共" + model.getPages() + "题");
                        tvSurveyTitle.setText((index + 1) + ". " + model.getRows().get(0).getTiMuContent());
                        Temp_list.clear();
                        Temp_list.addAll(model.getRows().get(0).getChoices());
                        tmuadapter.notifyDataSetChanged();
                        if (index == model.getTotal() - 1) {
                            tvNext.setText("下一步");
                        }
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, true);
    }

    /**
     * 选中题目
     */
    public void getChooseData(final int position, String choose_str, String c_id) {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.ChooseAnswer, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(SurveyActivity.this, "uid"));
        mRequest.add("assessId", getIntent().getStringExtra("id"));
        mRequest.add("tiMuId", tiMuId);
        mRequest.add("userChoice", choose_str);
        mRequest.add("choiceId", c_id);
        // 添加到请求队列
        CallServer.getRequestInstance().add(SurveyActivity.this, 0, mRequest,
                new CustomHttpListener(SurveyActivity.this, true, ChooseAnswerM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        ChooseAnswerM model = ((ChooseAnswerM) data);
                        tmuadapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, true);
    }

    /**
     * 选项列表
     */
    class TiMuAdapter extends BaseAdapter {
        private List<TiMuM.RowsBean.ChoicesBean> list;

        public TiMuAdapter(List<TiMuM.RowsBean.ChoicesBean> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View v, ViewGroup parent) {
            v = getLayoutInflater().inflate(R.layout.item_answer, null);
            LinearLayout ll_check = (LinearLayout) v.findViewById(R.id.ll_check);
            final CheckBox cb_check = (CheckBox) v.findViewById(R.id.cb_check);
            TextView tv_xuanxiang = (TextView) v.findViewById(R.id.tv_xuanxiang);
            View view_ban = (View) v.findViewById(R.id.line_padding);
            View view_man = (View) v.findViewById(R.id.line_match);
            tv_xuanxiang.setText(list.get(position).getChoice() + "  " + list.get(position).getChoiceContent());
            if (list.get(position).getIsSelect() == 1) {
                cb_check.setChecked(true);
            } else {
                cb_check.setChecked(false);
            }
            if (position == Temp_list.size() - 1) {
                view_ban.setVisibility(View.GONE);
                view_man.setVisibility(View.VISIBLE);
            } else {
                view_ban.setVisibility(View.VISIBLE);
                view_man.setVisibility(View.GONE);
            }
            ll_check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //单选
                    for (int i = 0; i < Temp_list.size(); i++) {
                        Temp_list.get(i).setIsSelect(0);
                    }
                    if (cb_check.isChecked() == false) {
                        cb_check.setChecked(true);
                        Temp_list.get(position).setIsSelect(1);
                        String choose_str = Temp_list.get(position).getChoice();
                        String choose_id = Temp_list.get(position).getChoiceId();
                        getChooseData(position, choose_str, choose_id);
                    } else {
                        cb_check.setChecked(true);
                    }

                    //多选
                   /* if (cb_check.isChecked() == true) {
                        cb_check.setChecked(true);
                        Temp_list.get(position).setIsSelect(0);
                    } else {
                        cb_check.setChecked(false);
                        Temp_list.get(position).setIsSelect(1);
                    }
                    StringBuffer buffer = new StringBuffer("");
                    for (int i = 0; i < Temp_list.size(); i++) {
                        if (Temp_list.get(i).getIsSelect() == 1) {
                            buffer.append(Temp_list.get(i).getChoice());
                            if (i != Temp_list.size() - 1) {
                                buffer.append(",");
                            }
                        }
                    }*/

//                    if (choose_str.endsWith(",")) {
//                        choose_str = choose_str.substring(0, choose_str.length() - 1);
//                    }

                }
            });
            return v;
        }

    }

    public void doClick(View v) {
        switch (v.getId()) {
            case R.id.tv_last://上一题
                tvNext.setText("下一题");
                //非空判断
                index--;
                if (index == 0) {//第一题
                    tvLast.setVisibility(View.GONE);
                } else {
                    tvLast.setVisibility(View.VISIBLE);
                }
                SetNewData(index);
                break;
            case R.id.tv_next://下一题
                //非空判断
                int a = 0;
                for (int i = 0; i < Temp_list.size(); i++) {
                    if (Temp_list.get(i).getIsSelect() == 1) {
                        a = 1;
                    }
                }
                if (a == 0) {
                    CommonUtil.showToask(SurveyActivity.this, "请选择答案后在进行下一步！");
                } else {
                    tvLast.setVisibility(View.VISIBLE);
                    if (("下一步").equals(tvNext.getText().toString())) { //提交
                        Intent in = new Intent(SurveyActivity.this, JinJiSurveyActivity.class);
                        in.putExtra("id", getIntent().getStringExtra("id"));
                        startActivity(in);
                    } else {
                        index++;
                        SetNewData(index);
                        if (index == pages - 1) {//最后一题
                            tvNext.setText("下一步");
                        }
                    }
                }
                break;
        }
    }

    //放置当前题目内容
    public void SetNewData(int now_index) {
        //设置头部题目提示
        tvSurveyNewnum.setText("第" + (now_index + 1) + "题");
//        tvSurveyTitle.setText((index + 1) + ". 您认为疼痛的原因是什么");
        getData();
    }

    /**
     * 返回
     */
    public void LayaBack() {
        ((ImageView) findViewById(R.id.imv_lay_back)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (index > 0) {
                    tvNext.setText("下一题");
                    //非空判断
                    index--;
                    if (index == 0) {//第一题
                        tvLast.setVisibility(View.GONE);
                    } else {
                        tvLast.setVisibility(View.VISIBLE);
                    }
                    SetNewData(index);
                } else {
                    finish();
                    overridePendingTransition(R.anim.pre_in, R.anim.pre_out);
                }

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (index > 0) {
                tvNext.setText("下一题");
                //非空判断
                index--;
                if (index == 0) {//第一题
                    tvLast.setVisibility(View.GONE);
                } else {
                    tvLast.setVisibility(View.VISIBLE);
                }
                SetNewData(index);
            } else {
                finish();
                overridePendingTransition(R.anim.pre_in, R.anim.pre_out);
            }
        }
        return false;
    }


}
